package lg.minecraft.plugin.worldprotect.gui;

import lg.minecraft.plugin.library.inventory.CancelInventoryContext;
import lg.minecraft.plugin.library.inventory.ClickInventoryContext;
import lg.minecraft.plugin.library.inventory.InventoryContext;
import lg.minecraft.plugin.library.inventory.LGInventory;
import org.bukkit.*;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.ArrayList;
import java.util.List;

/**
 * @author langle__
 * @version 1.0
 */
public class MainGUI extends LGInventory {

    private final List<World> worlds;

    public MainGUI() {
        super(6, "§f世界保护 §7| §f主界面");
        this.worlds = Bukkit.getWorlds();
    }

    @Override
    public void onInventoryOpen(CancelInventoryContext context) {
        Player player = context.getPlayer();
        World currentWorld = player.getWorld();
        for (int i = 0; i < worlds.size(); i++) {
            World world = worlds.get(i);
            ItemStack item = new ItemStack(Material.GRASS_BLOCK);
            ItemMeta meta = item.getItemMeta();
            if (meta == null) continue;
            meta.setDisplayName("§f" + world.getName());
            List<String> lore = new ArrayList<>();
            lore.add("§f左键 §7| §f设置保护");
            lore.add("§f右键 §7| §f设置游戏规则");
            lore.add("§fShift+点击 §7| §f传送此世界");
            meta.setLore(lore);
            if (currentWorld == world) {
                meta.addEnchant(Enchantment.BINDING_CURSE, 1, true);
                meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
            }
            item.setItemMeta(meta);
            inventory.setItem(i, item);
        }
    }

    @Override
    public void onInventoryClick(ClickInventoryContext context) {
        context.setCancelled(true);
        Player player = context.getPlayer();
        int slot = context.getSlot();
        ClickType click = context.getClick();

        if (slot >= worlds.size()) return;
        World world = worlds.get(slot);

        if (world == null) return;

        if (click == ClickType.SHIFT_LEFT || click == ClickType.SHIFT_RIGHT) {
            Location location = world.getSpawnLocation();
            player.teleport(location);
            player.playSound(location, Sound.ENTITY_PLAYER_LEVELUP, 1.0F, 1.8F);
        } else if (click == ClickType.LEFT) {
            player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1, 1);
            new SettingsGUI(world).openInventory(player);
        } else if (click == ClickType.RIGHT) {
            player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1, 1);
            new GameRuleGUI(world).openInventory(player);
        }

    }

    @Override
    public void onInventoryClose(InventoryContext context) {
    }

}
